package router

import (
	"gitee.com/baizhige/go-server-tempalte/common/constant"
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"gitee.com/baizhige/mongong-go"
	"gitee.com/baizhige/mongong-go/query"
	"go.mongodb.org/mongo-driver/bson"
)

func Modify(traceId string, router Router) *Router {
	id := router.Id
	repository := mongong.Coll[Router]()
	res, err := repository.FindById(id)
	if err != nil {
		log.ErrorTF(traceId, "Modify FindByID fail:%v", err)
		panic(constant.ErrRouterNotFind)
	}
	//不允许修改有些信息
	if router.Id != res.Id ||
		router.Project != res.Project ||
		router.Path != res.Path ||
		router.Method != res.Method {
		panic(constant.ErrRouterInvalidModify)
	}
	_, err = repository.ModifyOne(bson.M{"_id": id}, router)
	if err != nil {
		log.ErrorTF(traceId, "Modify One fail:%v", err)
		panic(constant.ErrSystem)
	}

	Refresh(&router)
	return &router
}

func Delete(traceId, id string) {
	repository := mongong.Coll[Router]()
	res, err := repository.FindById(id)
	if err != nil {
		log.ErrorTF(traceId, "Modify FindByID fail:%v", err)
		panic(constant.ErrRouterNotFind)
	}

	_, _ = repository.DeleteOne(query.Eq("_id", id))

	Clear(res)
	return
}
